<template>
  <div>
    <!-- 控制按钮 -->
    <el-button type="primary" @click="playAudio">播放音频</el-button>
    <el-button type="danger" @click="pauseAudio">暂停音频</el-button>
    <el-button type="warning" @click="destroyAudio">销毁音频</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import xl from '@/assets/mp3/xl.mp3';

// 创建音频对象
const audio = new Audio(xl);
audio.loop = true; // 设置循环播放

// 播放音频
const playAudio = () => {
  audio.play().catch(error => {
    console.error("播放音频时出错:", error);
  });
};

// 暂停音频
const pauseAudio = () => {
  audio.pause();
};

// 销毁音频
const destroyAudio = () => {
  audio.pause(); // 停止播放
  audio.currentTime = 0; // 重置播放时间
};

// 确保组件卸载时销毁音频对象
onUnmounted(() => {
  destroyAudio();
});
</script>


<style scoped>
/* 隐藏音频元素 */
audio {
  display: none;
}
</style>
